package com.linkstec.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class PostTest {
	
	private static final Logger logger = LogManager.getLogger();
	public static CloseableHttpClient closeableHttpClient = null;
	public static CloseableHttpAsyncClient closeableHttpAsyncClient = null;
    static  {
		// 设置代理IP、端口、协议（请分别替换）
		// HttpHost proxy = new HttpHost("172.16.0.1", 3128, "http");

		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(50000).setSocketTimeout(50000)
				.setConnectionRequestTimeout(1000)
				// .setProxy(proxy)
				.build();

		// 配置io线程
		IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
				.setIoThreadCount(Runtime.getRuntime().availableProcessors()).setSoKeepAlive(true).build();
		// 设置连接池大小
		ConnectingIOReactor ioReactor = null;
		try {
			ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
		} catch (IOReactorException e) {
			e.printStackTrace();
		}
		PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
		connManager.setMaxTotal(100);
		connManager.setDefaultMaxPerRoute(100);

		closeableHttpAsyncClient = HttpAsyncClients.custom().setConnectionManager(connManager)
				.setDefaultRequestConfig(requestConfig).build();
		
		closeableHttpClient = HttpClients.createDefault();
	   }
   private static class Thread1 implements Runnable{
       @Override
       public void run(){
    	   while (true) {
    		   
//    		   Thread t=Thread.currentThread();
//    		   System.out.println(t.getName());
    		   // 构造请求
    		   String urlPost = "http://localhost:8022/pushToBst";
    		   HttpPost httpPost = new HttpPost(urlPost);
//             httpPost.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
//             httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
//             httpPost.setHeader("Content-Type", "application/json;encoding=utf-8");
    		   httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//             StringEntity entity = null;
    		   UrlEncodedFormEntity entity = null;
    		   List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    		   try {
    			   nvps.add(new BasicNameValuePair("userId", "016193"));
    			   nvps.add(new BasicNameValuePair("pushTime", "2020-03-10 10:15:45:853"));
    			   nvps.add(new BasicNameValuePair("eMailTitle", "您有%一份未读邮件"));
    			   nvps.add(new BasicNameValuePair("sendUser", "016193,黄海满"));
    			   
    		   } catch (Exception e) {
    			   e.printStackTrace();
    		   }
    		   try {
    			   entity = new UrlEncodedFormEntity(nvps,"UTF-8");
    		   } catch (UnsupportedEncodingException e1) {
    			   e1.printStackTrace();
    		   }
//    		   logger.info(nvps);
    		   doPostSync(closeableHttpClient, httpPost, entity);
    		   // 休眠1秒
    		   try {
    			   Thread.sleep(1000);
    		   } catch (InterruptedException e) {
    			   e.printStackTrace();
    		   }
    	   }
    	   }
   }
   
	public static void main(String[] args) {

		/*// 构造请求
		String urlPost = "http://localhost:8022/pushToBst";
		HttpPost httpPost = new HttpPost(urlPost);
//      httpPost.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
//      httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
//      httpPost.setHeader("Content-Type", "application/json;encoding=utf-8");
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//      StringEntity entity = null;
        UrlEncodedFormEntity entity = null;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        try {
    	    nvps.add(new BasicNameValuePair("userId", "016193"));
    	    nvps.add(new BasicNameValuePair("pushTime", "2020-03-10 10:15:45:853"));
    	    nvps.add(new BasicNameValuePair("eMailTitle", "您有%一份未读邮件"));
    	    nvps.add(new BasicNameValuePair("sendUser", "016193,黄海满"));
    	  
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
	  	  entity = new UrlEncodedFormEntity(nvps,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
        logger.info(nvps);*/
       /* long start = System.currentTimeMillis();
        for (int i = 0; i < 200;i++) {
        	doPostAsync(client, httpPost, entity);
        }
        logger.info("异步调用总共花费时间:" + (System.currentTimeMillis() - start));*/
		/*while (true) {
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}*/
        /*try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}*/
		//模拟sum个客户端，每个都是同步调用
		int sum = 500;
        ExecutorService es = Executors.newFixedThreadPool(sum);
        
        Thread1 thread = new Thread1();
        es.execute(thread);
        for(int j = 0;j<sum;j++){
        	es.execute(new Thread1());
        }
        es.shutdown();
	}
	
	public static void doPostAsync(CloseableHttpAsyncClient client, HttpPost httpPost, StringEntity entity) {
		
	    httpPost.setEntity(entity);

	    //start
	    client.start();

	    //异步请求
	    client.execute(httpPost, new Back());
		
	}
	public static void doPostSync(CloseableHttpClient closeableHttpClient, HttpPost httpPost, StringEntity entity) {
		long start = System.currentTimeMillis();

		httpPost.setEntity(entity);
		//同步请求
		CloseableHttpResponse httpResponse = null;
		String content = null;
		try {
			httpResponse =closeableHttpClient.execute(httpPost);
			content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
			logger.info("cost is:" + (System.currentTimeMillis() - start) + ":"
					+ content);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	public static void doPost(CloseableHttpAsyncClient client, HttpPost httpPost) {
		StringEntity entity = null;
		try {
			String a = "{ \"index\": { \"_index\": \"test\", \"_type\": \"test\"} }\n"
					+ "{\"name\": \"上海\",\"age\":33}\n";
			entity = new StringEntity(a);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		httpPost.setEntity(entity);
		
		// start
		client.start();
		
		// 异步请求
		client.execute(httpPost, new Back());
		
	}

	public static void doGet(CloseableHttpAsyncClient client, HttpGet httpGet) {
		// start
		client.start();

		// 异步请求
		client.execute(httpGet, new Back());

	}

	static class Back implements FutureCallback<HttpResponse> {

		private long start = System.currentTimeMillis();

		Back() {
		}

		public void completed(HttpResponse httpResponse) {

			try {
				logger.info("cost is:" + (System.currentTimeMillis() - start) + ":"
						+ EntityUtils.toString(httpResponse.getEntity()));
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		public void failed(Exception e) {
			System.err.println(" error,cost is:" + (System.currentTimeMillis() - start) + ":" + e);
		}

		public void cancelled() {

		}
	}
}